import { createStore } from 'redux'

// 实现数据持久化
let userInfo = localStorage.getItem('userInfo')
try {
    userInfo = JSON.parse(userInfo) || {}
} catch (err) {
    userInfo = {}
}


const initState = {
    userInfo,
}

const reducer = (state, { type, payload }) => {
    let newState = { ...state }
    switch (type) {
        // {type:'login',payload:{...}}
        case 'login':
            newState.userInfo = payload
            localStorage.setItem('userInfo', JSON.stringify(payload))
            return newState;
        case 'logout':
            newState.userInfo = {}
            localStorage.removeItem('userInfo')
            return newState;
        
        default:
            return newState
    }
}

// 创建全局store仓库
const store = createStore(reducer, initState)

export default store;